<?php

namespace app\fly_pig\controller;


use think\Db;

include EXTEND_PATH.'taobao-feizhu'.DIRECTORY_SEPARATOR.'TopSdk.php';
require_once EXTEND_PATH."taobao-feizhu/QimenCloud/top/request/HuaerFlypigordersGetRequest.php";
require_once EXTEND_PATH."taobao-feizhu/QimenCloud/top/request/HuaerFlypigorderdetailsGetRequest.php";
require_once EXTEND_PATH."taobao-feizhu/QimenCloud/top/request/HuaerFlypigordercommentGetRequest.php";
require_once EXTEND_PATH."taobao-feizhu/QimenCloud/top/request/HuaerFlypigorderrefundGetRequest.php";
date_default_timezone_set('Asia/Shanghai');
/**
 *  飞猪类,主要从飞猪平台中获取有关飞猪订单信息
 * @author 邓汉炜
 * Class FlyPig
 * @package app\fly_pig\controller
 */
class FlyPig
{
    protected $appKey;
    protected $appSecret;
    protected $sessionKey;

    public function __construct()
    {
        $this->appKey = 26019993;
        $this->appSecret = '833dcacdacf1391759e6f4c801186573';
        $this->sessionKey = '6100521acb5e6d72c1d3b168be8aa1e04ee2f12cf20e1373166994525';
    }

    /**
     *  从奇门获取飞猪订单
     * @url /fly_pig/fly_pig/getFlyPigOrders
     */
    public function getFlyPigOrders($date = '', $page_no = 1)
    {
        $qiMenObj = new \QimenCloudClient();
        $qiMenObj->appkey = $this->appKey;
        $qiMenObj->secretKey = $this->appSecret;
//        $qiMenObj->gatewayUrl = "http://jushita.huaer.zanboon.com/fly_pig_order/index/getFlyPigOrder"; // 线上测试环境
        $qiMenObj->gatewayUrl = "http://huaer.huaertrip.com/fly_pig_order/index/getFlyPigOrder"; // 线上正式环境
        $qiMenObj->format = 'json';
        $qiMenRequest = new \HuaerFlypigordersGetRequest();
        $startTime = $date.' 00:00:00';
        $endTime = $date.' 23:59:59';
        $qiMenRequest->setStartTime($startTime);
        $qiMenRequest->setEndTime($endTime);
        $qiMenRequest->setPageNo($page_no);
        $getData = $qiMenObj->execute($qiMenRequest, $this->sessionKey);
        $getData = empty($getData) ? $getData : (array)$getData;
        $pageNo = 0; // 几页记录
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->select(6);
        if (!empty($getData['data']) && is_array($getData['data'])){
            foreach ($getData['data'] as $index => $getDatum) {
                $saveData = self::objectToArray($getDatum);
                $data = [];
                $data['tid'] = empty($saveData['tid'])?'':$saveData['tid'];
                $data['status'] = empty($saveData['status'])?'':$saveData['status'];
                $data['type'] = empty($saveData['type'])?'':$saveData['type'];
                $data['seller_nick'] = empty($saveData['seller_nick'])?'':$saveData['seller_nick'];
                $data['buyer_nick'] = empty($saveData['buyer_nick'])?'':$saveData['buyer_nick'];
                $data['created'] = empty($saveData['created'])?'':strtotime($saveData['created']);
                $data['modified'] = empty($saveData['modified'])?'':strtotime($saveData['modified']);
                $data['jdp_response'] = empty($saveData['jdp_response'])?'':$saveData['jdp_response'];
                $data['jdp_created'] = empty($saveData['jdp_created'])?'':strtotime($saveData['jdp_created']);
                $data['jdp_modified'] = empty($saveData['jdp_modified'])?'':strtotime($saveData['jdp_modified']);
                $jsonResponse = empty($saveData['jdp_response'])? '': json_decode($saveData['jdp_response'], true);
                if (!empty($jsonResponse)) {
                    $trade = empty($jsonResponse['trade_fullinfo_get_response']['trade']) ? '' : $jsonResponse['trade_fullinfo_get_response']['trade'];
                    if (!empty($trade)) {
                        $data['tid'] = empty($trade['tid_str'])?'':$trade['tid_str'];
                        $data['adjust_fee'] = empty($trade['adjust_fee'])?'':$trade['adjust_fee'];
                        $data['alipay_no'] = empty($trade['alipay_no'])?'':$trade['alipay_no'];
                        $data['available_confirm_fee'] = empty($trade['available_confirm_fee'])?'':$trade['available_confirm_fee'];
                        $data['buyer_cod_fee'] = empty($trade['buyer_cod_fee'])?'':$trade['buyer_cod_fee'];
                        $data['buyer_message'] = empty($trade['buyer_message'])?'':$trade['buyer_message'];
                        $data['buyer_rate'] = empty($trade['buyer_rate'])?0:1;
                        $data['cod_status'] = empty($trade['cod_status'])?'':$trade['cod_status'];
                        $data['coupon_fee'] = empty($trade['coupon_fee'])?'':$trade['coupon_fee'];
                        $data['consign_time'] = empty($trade['consign_time'])?'':strtotime($trade['consign_time']);
                        $data['discount_fee'] = empty($trade['discount_fee'])?'':$trade['discount_fee'];
                        $data['has_post_fee'] = empty($trade['has_post_fee'])?0:1;
                        $data['is_daixiao'] = empty($trade['is_daixiao'])?0:1;
                        $data['is_sh_ship'] = empty($trade['is_sh_ship'])?0:1;
                        $data['new_presell'] = empty($trade['new_presell'])?0:1;
                        $data['orders'] = empty($trade['orders'])?'': json_encode($trade['orders'],JSON_UNESCAPED_UNICODE);
                        $orderData = empty($trade['orders']['order']) ? '': $trade['orders']['order'];
                        if (!empty($orderData)){
                            $data['cid'] = empty($orderData[0]['cid'])?'':$orderData[0]['cid'];
                            $data['divide_order_fee'] = empty($orderData[0]['divide_order_fee'])?'':$orderData[0]['divide_order_fee'];
                            $data['is_oversold'] = empty($orderData[0]['is_oversold'])?0:1;
                            $data['oid'] = empty($orderData[0]['oid_str'])?'':$orderData[0]['oid_str'];
                            $data['order_from'] = empty($orderData[0]['order_from'])?'':$orderData[0]['order_from'];
                            $data['payment'] = empty($orderData[0]['payment'])?'':$orderData[0]['payment'];
                            $data['pic_path'] = empty($orderData[0]['pic_path'])?'':$orderData[0]['pic_path'];
                            $data['price'] = empty($orderData[0]['price'])?'':$orderData[0]['price'];
                            $data['refund_status'] = empty($orderData[0]['refund_status'])?'':$orderData[0]['refund_status'];
                            $data['refund_status'] = empty($orderData[0]['refund_status'])?'':$orderData[0]['refund_status'];
                            $data['seller_rate'] = empty($orderData[0]['seller_rate'])?0:1;
                            $data['seller_type'] = empty($orderData[0]['seller_type'])?'':$orderData[0]['seller_type'];
                            $data['shipping_type'] = empty($orderData[0]['shipping_type'])?'':$orderData[0]['shipping_type'];
                            $data['sku_id'] = empty($orderData[0]['sku_id'])?'':$orderData[0]['sku_id'];
                            $data['sku_properties_name'] = empty($orderData[0]['sku_properties_name'])?'':$orderData[0]['sku_properties_name'];
                            $data['timeout_action_time'] = empty($orderData[0]['timeout_action_time'])?'':strtotime($orderData[0]['timeout_action_time']);
                            $data['title'] = empty($orderData[0]['title'])?'':$orderData[0]['title'];
                            $data['num'] = empty($orderData[0]['num'])?'':$orderData[0]['num'];
                            $data['total_fee'] = empty($orderData[0]['total_fee'])?'':$orderData[0]['total_fee'];
                        }
                        $data['pay_time'] = empty($trade['pay_time'])?'':strtotime($trade['pay_time']);
                        $data['post_fee'] = empty($trade['post_fee'])?'':$trade['post_fee'];
                        $data['received_payment'] = empty($trade['received_payment'])?'':$trade['received_payment'];
                        $data['promotion_details'] = empty($trade['promotion_details'])?'':json_encode($trade['promotion_details'],JSON_UNESCAPED_UNICODE);
                        $data['num_iid'] = empty($trade['num_iid'])?'':$trade['num_iid'];
                    }
                }
                // 如果存在,更新数据;如果不存在,添加数据
                $flyPigOrder = Db::name('fly_pig_order')->where('tid',$data['tid'])->find();
                if ($flyPigOrder){
                    Db::name('fly_pig_order')->where('id',$flyPigOrder['id'])->find();
                }else{
                    Db::name('fly_pig_order')->strict(false)->insert($data);
                }
            }
            if (!empty($getData['total_result']) && $getData['total_result'] > 100){
                $pageNo = ceil($getData['total_result']/100);
                // 设置键的字符串
                $val = $redis->get($date);
                if (empty($val)){
                    $redis->set($date, 1);
                }else{
                    $redis->incr($date);
                }
                // 把分页存进redis中
                $date1 = $date.'-'.$pageNo;
                if ($pageNo < $page_no && date('Y-m-d', time()) > $date){
                    $redis->rPush('order_date1', $date);
                }else{
                    $redis->rPush('order_date', $date1);
                }
            }elseif (date('Y-m-d', time()) == $date){ // 不够100条
                $redis->rPush('order_date', $date);
            }else {
                $redis->rPush('order_date1', $date);
            }
        }else{
            if (!empty($getData['code'])){ // 奇门报错
                if ($page_no > 1){
                    $date = $date . '-'.$page_no;
                }
                $redis->rPush('order_date', $date);
                logs('feizhu-order-error', date('Y-m-d H:i:d', time()));
                logs('feizhu-order-error', $getData);
            }elseif (is_array($getData['data']) && date('Y-m-d', time()) == $date){
                if ($page_no > 1){
                    $date = $date . '-'.$page_no;
                }
                $redis->rPush('order_date', $date);
            }else{
                $redis->rPush('order_date1', $date);
            }
        }

    }


    /**
     * 将object(stdClass)数据转换成数组
     */
    public static function objectToArray($array = [])
    {
        if (!empty($array)){
            if (is_object($array)){
                $array = (array)$array;
            }elseif (is_array($array)){
                foreach ($array as $index => $item) {
                    $array[$index] = self::objectToArray($item);
                }
            }
            return $array;
        }else {
            $array = [];
            return $array;
        }
    }

    /**
     *  从奇门同步飞猪订单详情
     * @url /fly_pig/fly_pig/syncFlyPigDetails
     */
    public function syncFlyPigDetails($orderId = '',$create_time = '')
    {
        $qiMenObj = new \QimenCloudClient();
        $qiMenObj->appkey = $this->appKey;
        $qiMenObj->secretKey = $this->appSecret;
//        $qiMenObj->gatewayUrl = "http://jushita.huaer.zanboon.com/fly_pig_order/index/getFlyPigOrderDetails";
        $qiMenObj->gatewayUrl = "http://huaer.huaertrip.com/fly_pig_order/index/getFlyPigOrderDetails"; // 线上正式环境
        $qiMenObj->format = 'json';
        $qiMenRequest = new \HuaerFlypigorderdetailsGetRequest();
        if (!empty($create_time)){
            $create_time = strtotime($create_time);
        }
        $qiMenRequest->setOrderId($orderId);
        $qiMenRequest->setCreateTime($create_time);
        $qiMenResponse = $qiMenObj->execute($qiMenRequest, $this->sessionKey);
        $getData = empty($qiMenResponse) ? '' : (array)$qiMenResponse;
        if (!empty($create_time)){
            $create_time = date('Y-m-d', $create_time);
        }
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->select(6);
        if (!empty($getData['data']) && array_key_exists('data', $getData)){
            $data = (array)$getData['data'];
            $travellerData = empty($getData['traveller'])?'':$getData['traveller'];
            if (!empty($orderId)){
                $this->saveFlyPigOrderDetail($data, $travellerData);
            }elseif (!empty($create_time)){
                foreach ($data as $index2 => $datum2) {
                    $datum2 = (array)$datum2;
                    $travellerData = $datum2['travellerData'];
                    unset($datum2['travellerData']);
                    $this->saveFlyPigOrderDetail($datum2,$travellerData);
                }
            }
            if (date('Y-m-d', time()) == $create_time){
                $redis->rPush('order_detail_date', $create_time);
            }else{
                $redis->rPush('order_detail_date1', $create_time);
            }
        }else{
            if (date('Y-m-d', time()) > $create_time && empty($getData['data']) && array_key_exists('data', $getData)){
                $redis->rPush('order_detail_date1', $create_time);
            }else{
                $redis->rPush('order_detail_date', $create_time);
            }
            logs('fly_pig_order_error', date('Y-m-d H:i:s', time()));
            logs('fly_pig_order_error', $getData);
        }
    }

    /**
     *  先将单个订单详情旅客详情数据保存到飞猪订单详情表和飞猪订单旅客表中,
     *  再把相关数据保存到订单和订单旅客中
     */
    public function saveFlyPigOrderDetail($data = [], $travellerData = [])
    {
        if (!empty($data)){
            unset($data['id']);
            $finds = Db::name('fly_pig_order_detail')->where('order_id', $data['order_id'])->find();
            $getOrderDetailId = '';
            if ($finds){
                Db::name('fly_pig_order_detail')->where('order_id', $data['order_id'])->strict(false)->update($data);
            }else{
                $getOrderDetailId = Db::name('fly_pig_order_detail')->strict(false)->insertGetId($data);
            }
            $travellers = [];
            if (!empty($travellerData)){
                foreach ($travellerData as $index => $travellerDatum) {
                    $travellerDatum = (array)$travellerDatum;
                    unset($travellerDatum['id']);
                    if (empty($getOrderDetailId)){
                        unset($travellerDatum['fly_pig_order_detail_id']);
                        Db::name('fly_pig_order_traveller')->where('order_id', $data['order_id'])->strict(false)->update($travellerDatum);
                    }else{
                        $travellerDatum['fly_pig_order_detail_id'] = $getOrderDetailId;
                        Db::name('fly_pig_order_traveller')->strict(false)->insert($travellerDatum);
                    }
                    $travellers[] = $travellerDatum;
                }
            }
            $saveOrder = [];
            $saveOrder['order_id'] = empty($data['order_id'])?'':$data['order_id'];
            $saveOrder['order_status'] = empty($data['status'])?'':self::getOrderStatus($data['status']);
            if (!empty($data['refund_status']) && $data['refund_status'] != 'NO_REFUND'){ // 有退款
                $saveOrder['isrefund'] = 1;
                $saveOrder['refund_status'] = empty($data['refund_status'])?'':self::getOrderRefuseStatus($data['refund_status']);
            }
            $payment = empty($data['payment'])? 0 : $data['payment']/100;
            $saveOrder['money'] = empty($data['payment']) ? '' : $payment;
            $saveOrder['title'] = empty($data['item_title']) ? '' : $data['item_title'];
            $saveOrder['sales_name'] = empty($data['item_title']) ? '' : $data['item_title'];
            $received_payment = empty($data['received_payment']) ? '' : $data['received_payment']/100;
            $saveOrder['refund_money'] =$received_payment;
            $saveOrder['platform'] = 'Fliggy';
            $saveOrder['start_time'] = empty($data['trip_start_date'])?0:$data['trip_start_date'];
            $saveOrder['end_time'] = empty($data['trip_end_date'])?0:$data['trip_end_date'];
            $name = empty($data['buyer_message'])? '' : self::getBuyerName($data['buyer_message']);
            $name = empty($name) && !empty($data['buyer_nick']) ? $data['buyer_nick'] : $name;
            $saveOrder['booking_people_name'] = $name;
            $saveOrder['booking_people_email'] = empty($data['buyer_email'])?'':$data['buyer_email'];
            $saveOrder['booking_people_phone'] = empty($data['buyer_phone'])?self::getBuyerPhone($data['buyer_message']):$data['buyer_phone'];
            $saveOrder['booking_people_remark'] = empty($data['buyer_message'])?'':$data['buyer_message'];
            $saveOrder['ctime'] = empty($data['created_time'])?'':$data['created_time'];
            $saveOrder['sku_name'] = empty($data['sku_properties'])?'':$data['sku_properties'];
            $totalPrice = 0;
            if (!empty($data['price']) && !empty($data['num'])){
                $totalPrice = ($data['price']/100) * $data['num'] ;
            }
            $saveOrder['total_price'] = $totalPrice;
            $saveOrder['payment_fee'] = $payment;
            // 平台优惠
            $reduceMfw = empty($data['discount_fee']) ? 0 : $data['discount_fee']/100;
            if (!empty($data['pay_info']) && empty($reduceMfw)){
                $payInfo = json_decode($data['pay_info'], true);
                if (is_array($payInfo) && !empty($payInfo['discount_fee'])){
                    $reduceMfw = $payInfo['discount_fee']/100;
                }
            }
            $saveOrder['reduce_mfw'] = $reduceMfw;
            $saveOrder['dispose_status'] = 'no_contact';
            $saveOrder['color'] = empty($data['seller_flag'])? 10 : self::getFlagColor($data['seller_flag']);
            $saveOrder['num'] = empty($data['num'])? 0 : $data['num'];
            $saveOrder['isallot'] = 0;

            $flyPigOrder = Db::name('fly_pig_order')->where('tid',$saveOrder['order_id'])->find();
            if ($flyPigOrder){
                $saveOrder['sku_id'] = $flyPigOrder['sku_id'];
            }
            // 保存进订单
            $find = Db::name('order')->where('order_id', $saveOrder['order_id'])
                ->where('platform','Fliggy')->find();
            if ($find){
                unset($saveOrder['order_status']);
                Db::name('order')->where('order_id', $saveOrder['order_id'])
                    ->strict(false)->update($saveOrder);
            }else{
                Db::name('order')->strict(false)->insertGetId($saveOrder);
            }
            // 组装旅客数据
            if (!empty($travellers)){
                foreach ($travellers as $index8 => $traveller8) {
                    $oid = Db::name('order')->where('order_id', $saveOrder['order_id'])->value('id');
                    $saveTraveller = [];
                    $saveTraveller['oid'] = $oid;
                    $saveTraveller['name'] = empty($traveller8['name'])?'':$traveller8['name'];
                    $saveTraveller['phone'] = empty($traveller8['phone'])? '' : $traveller8['phone'];
                    $saveTraveller['id_card'] = empty($traveller8['credential_no'])? '' :$traveller8['credential_no'];
                    $find = Db::name('order_traveler')->where('oid', $oid)->where('id_card',$saveTraveller['id_card'])->find();
                    if ($find){
                        Db::name('order_traveler')->where('oid', $oid)->where('id_card',$saveTraveller['id_card'])->strict(false)->update($saveTraveller);
                    }else{
                        Db::name('order_traveler')->strict(false)->insert($saveTraveller);
                    }
                }
            }
        }
    }

    /**
     *  获取订单状态
     */
    public static function getOrderStatus($val = '')
    {
        $ret = '';
        if (!empty($val)){
            switch ($val){
                case 'WAIT_BUYER_PAY': $ret = 'pay_for'; break;
                case 'WAIT_SELLER_SEND_GOODS': $ret = 'pending'; break;
                case 'TRADE_CLOSED': $ret = 'close'; break;
                case 'TRADE_CLOSED_BY_TAOBAO': $ret = 'close'; break;
                case 'TRADE_FINISHED': $ret = 'close'; break; // 交易成功
                default: $ret = 'pending';
            }
        }
        return $ret;
    }

    /**
     *  获取订单退款状态
     */
    public static function getOrderRefuseStatus($val = '')
    {
        $ret = '';
        if (!empty($val)){
            switch ($val){
                case 'WAIT_SELLER_AGREE': $ret = 'check'; break;
                case 'WAIT_BUYER_RETURN_GOODS': $ret = 'refunded'; break;
                case 'WAIT_SELLER_CONFIRM_GOODS': $ret = 'refunded'; break;
                case 'SELLER_REFUSE_BUYER': $ret = 'rejected'; break;
                case 'CLOSED': $ret = 'rejected'; break;
                case 'SUCCESS': $ret = 'refunded'; break;
            }
        }
        return $ret;
    }

    /**
     *  获取姓名
     */
    public static function getBuyerName($val = '')
    {
        $name = '';
        if (!empty($val)) {
            $val = explode(' ', $val);
            foreach ($val as $key => $value) {
                $value = explode(':', $value);
                if (count($value) != 1 && $value[0] == '姓名') {
                    $name = $value[1];
                }
            }
        }
        return $name;
    }
    
    /**
     *  获取旗帜颜色
     */
    public static function getFlagColor($val = '')
    {
        $ret = 10;
        if (!empty($val)){
            switch ($val){
                case 1: $ret = 1;break;
                case 2: $ret = 3; break;
                case 3: $ret = 4; break;
                case 4: $ret = 5; break;
                case 5: $ret = 6; break;
                default: $ret = 1;
            }
        }
        return $ret;
    }

    /**
     *  获取收集联系人电话
     */
    public static function getBuyerPhone($val = '')
    {
        $name = '';
        if (!empty($val)) {
            $val = explode(' ', $val);
            foreach ($val as $key => $value) {
                $value = explode(':', $value);
                if (count($value) != 1 && $value[0] == '电话') {
                    $name = $value[1];
                }
            }
        }
        return $name;
    }

    /**
     *  获取飞猪订单评论
     * @url /fly_pig/fly_pig/syncFlyPigOrderComment
     */
    public function syncFlyPigOrderComment($create_time = '', $page_no = 1)
    {
        $qiMenObj = new \QimenCloudClient();
        $qiMenObj->appkey = $this->appKey;
        $qiMenObj->secretKey = $this->appSecret;
//        $qiMenObj->gatewayUrl = 'http://jushita.huaer.zanboon.com/fly_pig_order/index/getFlyPigOrderComment';
        $qiMenObj->gatewayUrl = "http://huaer.huaertrip.com/fly_pig_order/index/getFlyPigOrderComment"; // 线上正式环境
        $qiMenObj->format = 'json';
        $qiMenRequest = new \HuaerFlypigordercommentGetRequest();
        $qiMenRequest->setCreateTime($create_time);
        $qiMenRequest->setPageNo($page_no);
        $responseData = $qiMenObj->execute($qiMenRequest, $this->sessionKey);
        $getData = empty($responseData)?'': (array)$responseData;
        if (!empty($create_time)){
            $create_time = date('Y-m-d', $create_time);
        }
        if ($page_no > 1){
            $create_time = $create_time.'-'.$page_no;
        }
        if (!empty($getData) && array_key_exists('data',$getData)){
            if (!empty($getData['data'])){
                foreach ($getData['data'] as $index => $datum) {
                    $datum = (array)$datum;
                    unset($datum['id']);
                    $find = Db::name('fly_pig_comment')->where('oid',$datum['oid'])->find();
                    if ($find){
                        Db::name('fly_pig_comment')->where('oid',$datum['oid'])->strict(false)->update($datum);
                    }else{
                        Db::name('fly_pig_comment')->strict(false)->insert($datum);
                    }
                    $find = Db::name('fly_pig_comment')->where('oid',$datum['oid'])->find();
                    $order = Db::name('order')->where('order_id',$datum['oid'])->find();
                    // 组装订单评价
                    $orderComment = [];
                    $orderComment['oid'] = empty($datum['oid'])?'':$datum['oid'];
                    $orderComment['platform'] = 'Fliggy';
                    $orderComment['comment_id'] = $find['id'];
                    $orderComment['user_name'] = empty($order['booking_people_name'])&&!empty($datum['nick'])? $datum['nick']:$order['booking_people_name'];
                    $orderComment['comment'] = empty($datum['content'])? '':$datum['content'];
                    $orderComment['shop_name'] = empty($datum['rated_nick'])? '青海精灵国旅专营店':$datum['rated_nick'];
                    $orderComment['reply'] = empty($datum['reply'])? '':$datum['reply'];
                    $orderComment['create_time'] = empty($datum['created'])? '':$datum['created'];
                    if (!empty($datum['result'])){
                        switch ($datum['result']){
                            case 'good': $orderComment['comment_status'] = 1;break;
                            default: $orderComment['comment_status'] = 2;
                        }
                    }
                    $find = Db::name('order_evaluate')->where('oid', $orderComment['oid'])->find();
                    if ($find){
                        Db::name('order_evaluate')->where('oid', $orderComment['oid'])->strict(false)->update($orderComment);
                    }else{
                        Db::name('order_evaluate')->strict(false)->insert($orderComment);
                    }
                    $is_review = Db::name('order')
                        ->where('order_id',$orderComment['oid'])
                        ->value('is_review');
                    if (empty($is_review)){
                        Db::name('order')
                            ->where('order_id',$orderComment['oid'])
                            ->where('order_status','issue')
                            ->where('dispose_status','normal_travel')
                            ->update(['is_review'=>1]);
                    }
                }
            }
        }else{
            logs('syncFlyPigOrderCommentError', date('Y-m-d H:i:s', time()));
            logs('syncFlyPigOrderCommentError', $getData);
        }
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->select(7);
        // 保存日期页数进redis
        if (!empty($getData['total_result']) && $getData['total_result'] > 180){
            $pageNo = ceil($getData['total_result']/100);
            // 设置键的字符串
            $val = $redis->get($create_time);
            if (empty($val)){
                $redis->set($create_time, 1);
            }
            // 把分页存进redis中
            $date = $create_time.'-'.$pageNo;
            $redis->rPush('order_comment_date', $date);
        }elseif (empty($getData['code'])){ // 不是奇门报错
            if (date('Y-m-d', time()) == $create_time){
                $redis->rPush('order_comment_date', $create_time);
            }elseif(empty($getData['data']) && date('Y-m-d', time()) > $create_time){
                $redis->rPush('order_comment_date1', $create_time);
            }
        }elseif (!empty($getData['code'])){ // 是奇门报错
            $redis->rPush('order_comment_date', $create_time);
        }
    }

    /**
     *  从奇门获取退款订单
     * @url fly_pig/fly_pig/getFlyPigOrderRefund
     */
    public function getFlyPigOrderRefund($create_time = '', $modify_time = '', $order_id = '')
    {
        $qiMenObj = new \QimenCloudClient();
        $qiMenObj->appkey = $this->appKey;
        $qiMenObj->secretKey = $this->appSecret;
//        $qiMenObj->gatewayUrl = 'http://jushita.huaer.zanboon.com/fly_pig_order/index/getFlyPigRefusedOrder';
        $qiMenObj->gatewayUrl = "http://huaer.huaertrip.com/fly_pig_order/index/getFlyPigRefusedOrder"; // 线上正式环境
        $qiMenObj->format = 'json';
        $qiMenRequest = new \HuaerFlypigorderrefundGetRequest(); // 创建退款请求对象
        $qiMenRequest->setCreateTime($create_time);
        $qiMenRequest->setModifyTime($modify_time);
        $qiMenRequest->setOrderId($order_id);
        $data = $qiMenObj->execute($qiMenRequest, $this->sessionKey);
        $data = (array)$data;
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->select(6);
//        dump($data);
        if (!empty($data['data']) && array_key_exists('data', $data)){
            foreach ($data['data'] as $index => $datum) {
                $datum = (array)$datum;
                $saveData = [];
                $saveData['seller_nick'] = empty($datum['seller_nick'])?'':$datum['seller_nick'];
                $saveData['buyer_nick'] = empty($datum['buyer_nick'])?'':$datum['buyer_nick'];
                $saveData['status'] = empty($datum['status'])?'':$datum['status'];
                $saveData['created'] = empty($datum['created'])?'':strtotime($datum['created']);
                $saveData['modified'] = empty($datum['modified'])?'':strtotime($datum['modified']);
                $saveData['jdp_created'] = empty($datum['jdp_created'])?'':strtotime($datum['jdp_created']);
                $saveData['jdp_modified'] = empty($datum['jdp_modified'])?'':strtotime($datum['jdp_modified']);
                $saveData['jdp_hashcode'] = empty($datum['jdp_hashcode'])?'':$datum['jdp_hashcode'];
                $saveData['jdp_response'] = empty($datum['jdp_response'])?'':$datum['jdp_response'];
                if (!empty($datum['jdp_response'])){
                    $jdpResponse = json_decode($datum['jdp_response'], true,512,JSON_BIGINT_AS_STRING);
                    if (!empty($jdpResponse['refund_get_response']) && !empty($jdpResponse['refund_get_response']['refund'])){
                        $refundData = $jdpResponse['refund_get_response']['refund'];
                        $saveData['refund_id'] = empty($refundData['refund_id'])?'':$refundData['refund_id'];
                        $saveData['tid'] = empty($refundData['tid'])?'':$refundData['tid'];
                        $saveData['oid'] = empty($refundData['oid'])?'':$refundData['oid'];
                        $saveData['advance_status'] = empty($refundData['advance_status'])?'':$refundData['advance_status'];
                        $saveData['alipay_no'] = empty($refundData['alipay_no'])?'':$refundData['alipay_no'];
                        $saveData['attribute'] = empty($refundData['attribute'])?'':$refundData['attribute'];
                        $saveData['cs_status'] = empty($refundData['cs_status'])?'':$refundData['cs_status'];
                        $saveData['desc'] = empty($refundData['desc'])?'':$refundData['desc'];
                        $saveData['good_status'] = empty($refundData['good_status'])?'':$refundData['good_status'];
                        $saveData['num'] = empty($refundData['num'])?'':$refundData['num'];
                        $saveData['num_iid'] = empty($refundData['num_iid'])?'':$refundData['num_iid'];
                        $saveData['operation_contraint'] = empty($refundData['operation_contraint'])?'':$refundData['operation_contraint'];
                        $saveData['order_status'] = empty($refundData['order_status'])?'':$refundData['order_status'];
                        $saveData['payment'] = empty($refundData['payment'])?'':$refundData['payment'];
                        $saveData['price'] = empty($refundData['price'])?'':$refundData['price'];
                        $saveData['reason'] = empty($refundData['reason'])?'':$refundData['reason'];
                        $saveData['refund_fee'] = empty($refundData['refund_fee'])?'':$refundData['refund_fee'];
                        $saveData['refund_phase'] = empty($refundData['refund_phase'])?'':$refundData['refund_phase'];
                        $saveData['refund_version'] = empty($refundData['refund_version'])?'':$refundData['refund_version'];
                        $saveData['sku'] = empty($refundData['sku'])?'':$refundData['sku'];
                        $saveData['title'] = empty($refundData['title'])?'':$refundData['title'];
                        $saveData['total_fee'] = empty($refundData['total_fee'])?'':$refundData['total_fee'];
                        $saveData['has_good_return'] = empty($refundData['has_good_return'])?0:1;
                    }
                }
                $find = Db::name('fly_pig_refund_order')->where('tid', $saveData['tid'])->find();
                if ($find){
                    if ($find['status'] != $saveData['status']){
                        // 更新退款订单的状态
                        $refundOrder = [];
                        $refundOrder['isrefund'] = 1;
                        $refundOrder['refund_status'] = empty($saveData['status'])?'check':self::getOrderRefuseStatus($saveData['status']);
                        $refundOrder['refund_money'] = empty($saveData['refund_fee'])?'':$saveData['refund_fee'];
                        $refundOrder['refund_reason'] = empty($saveData['reason'])?'':$saveData['reason'];
                        $find = Db::name('order')->where('order_id', $saveData['oid'])->find();
                        if ($find){
                            Db::name('order')->where('order_id', $saveData['oid'])->strict(false)->update($refundOrder);
                        }
                    }
                    Db::name('fly_pig_refund_order')->where('tid', $saveData['tid'])->strict(false)->update($saveData);
                }else{
                    Db::name('fly_pig_refund_order')->strict(false)->insert($saveData);
                    // 更新退款订单的状态
                    $refundOrder = [];
                    $refundOrder['isrefund'] = 1;
                    $refundOrder['refund_status'] = empty($saveData['status'])?'check':self::getOrderRefuseStatus($saveData['status']);
                    $refundOrder['refund_money'] = empty($saveData['refund_fee'])?'':$saveData['refund_fee'];
                    $refundOrder['refund_reason'] = empty($saveData['reason'])?'':$saveData['reason'];
                    $find = Db::name('order')->where('order_id', $saveData['oid'])->find();
                    if ($find){
                        Db::name('order')->where('order_id', $saveData['oid'])->strict(false)->update($refundOrder);
                    }
                }
            }
            // 数据推送创建时间
            if (!empty($create_time) && $create_time == date('Y-m-d', time())){
                $redis->rPush('order_refund_date', $create_time);
            }else{
                $redis->rPush('order_refund_date1', $create_time);
            }
            if (!empty($modify_time) && $modify_time == date('Y-m-d', time())){
                $redis->rPush('order_refund_modify_date', $modify_time);
            }else{
                $redis->rPush('order_refund_modify_date1', $modify_time);
            }
        }else{
            if (!empty($create_time) && $create_time == date('Y-m-d',time())){
                $redis->rPush('order_refund_date', $create_time);
            }elseif (!empty($create_time) && $create_time != date('Y-m-d', time()) && empty($data['data'])){
                $redis->rPush('order_refund_date1', $create_time);
            }else{
                $redis->rPush('order_refund_date', $create_time);
            }
            if (!empty($modify_time) && $modify_time == date('Y-m-d', time())){
                $redis->rPush('order_refund_modify_date', $modify_time);
            }elseif (!empty($modify_time) && $modify_time != date('Y-m-d', time()) && empty($data['data'])){
                $redis->rPush('order_refund_modify_date1', $modify_time);
            }else{
                $redis->rPush('order_refund_modify_date', $modify_time);
            }
            if (!empty($data['code'])) {
                logs('feizhu-tuikuan-order-error', date('Y-m-d H:i:s', time()));
                logs('feizhu-tuikuan-order-error', $data);
            }
        }
    }

    /**
     *  获取退款订单状态
     */
    public static function getOrderRefudeStatus($val = '')
    {
        $ret = '';
        if (!empty($val)){
            switch ($val){
                case 'WAIT_SELLER_AGREE': $ret = 'check'; break;
                case 'WAIT_BUYER_RETURN_GOODS': $ret = 'refunding'; break;
                case 'WAIT_SELLER_CONFIRM_GOODS': $ret = 'refunding'; break;
                case 'SELLER_REFUSE_BUYER': $ret = 'rejected'; break;
                case 'CLOSED': $ret = 'rejected'; break;
                case 'SUCCESS': $ret = 'refunded'; break;
            }
        }
        return $ret;
    }

}
